/** */
package com.skwyb.form.core;

import com.alibaba.fastjson.JSON;
import com.skwyb.form.constants.ResultCode;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(
            HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(
            HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    /** */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean flag = false;

        String requestURI = request.getRequestURI();
        String referer = request.getHeader("referer");
        System.out.println(requestURI);
        System.out.println(referer);

        if (requestURI.contains("/portal/user/")) {
//            UserInfo user = SessionUtil.getUser(request.getSession()); // 获取session 中的用户
//            if (user != null) {
//                flag = true;
//            }
        } else {
            flag = true;
        }

        if (!flag) {
            String jsCode = "";
            boolean isAjaxRequest = isAjaxRequest(request);
            if (isAjaxRequest) {
                jsCode = JSON.toJSONString(new ObjectResult(ResultCode.SESSION_TIME_OUT));
                response.setContentType("application/json");
            } else {
                jsCode =
                        "<script type='text/javascript'>"
                                + "var p=window;while(p!=p.parent){p=p.parent; } p.location.href='"
                                + request.getContextPath()
                                + "/index.html'</script>";
            }
            PrintWriter writer = response.getWriter();
            writer.print(jsCode);
            writer.flush();
            writer.close();
        }
        return flag;
    }

    /**
     * 判断是否为Ajax请求
     *
     * @param request HttpServletRequest
     * @return 是true, 否false
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
    }
}
